// index.js
// 获取应用实例
const app = getApp()
import {
    goAppList,
    goToContract,
    dateFormat
} from '../../utils/util'
import user from '../../utils/user.js'
import {
    getWorkTipList,
    putLeftDelete,
    checkHomeList
} from '../../api/app.js'
import {
    getisnewmessageapi
} from '../../api/app'
Page({
    data: {
        shareStatus: false,
        userId: '',
        showBtn: false,
        startX: '',
        startY: '',
        projectList: [],
        totalCount: 0,
        isactive: false,
        srcolling: false,
        timer: null,
    },
    static: {
        pageNum: 1,
        pageSize: 20,
        hasNextPage: true,
        totalCount: 0
    },
    bindscrollfn(e) {
        this.setData({
            srcolling: true
        })
        if (this.data.timer) clearTimeout(this.data.timer)
        this.data.timer = setTimeout(() => {
            this.setData({
                srcolling: false
            })
        }, 1000)
    },
    async onShow() {
        console.log(wx.getSystemInfoSync)
        console.log(app.globalData)
        this.getTabBar().setData({
            selected: 1
        })
        try {
            await user.waitLogin()
            this.setData({
                userId: user.userId,
            })
            if (this.data.totalCount == 0) {
                this.getProjectList()
            } else {
                try {
                    const result = await checkHomeList()
                    if (result !== this.data.totalCount) {
                        this.data.projectList = []
                        this.static.pageNum = 1
                        this.static.hasNextPage = true
                        this.getProjectList()
                    }
                } catch (e) {
                    console.log(e)
                }
            }
            let res = await getisnewmessageapi()
            console.log(res, 'csj11')
            this.setData({
                // isactive: falsetomessage
                isactive: res
            })
        } catch (e) {
            this.setData({
                userId: '',
                projectList: [],
                showBtn: true
            })
        }
    },
    async getProjectList() {
        const result = await getWorkTipList({
            id: user.userId,
            pageNum: this.static.pageNum,
            pageSize: this.static.pageSize
        })
        if (!result.hasNextPage) {
            this.static.hasNextPage = false
        }
        console.log(this.data, 'data')
        this.data.totalCount = result.totalCount
        let arr = []
        arr.push(...this.data.projectList)
        arr.push(...result.list)
        this.data.projectList.map(item => {
            item.x = 0
        })
        this.setData({
            projectList: arr
        })
    },
    onArriveBottom() {
        if (!this.static.hasNextPage) return
        this.static.pageNum += 1
        this.getProjectList()
    },
    // 加入团队
    async joinProjectAsCode() {
        // if (!user.userId) {
        //     await app.confirm('您还未注册，是否立即前往注册？')
        //     this.login()
        //     return 0
        // }
        wx.navigateTo({
            url: '/pages/code/code'
        })
    },

    // 扫一扫
    async scan() {
        // if (!user.userId) {
        //     await app.confirm('您还未注册，是否立即前往注册？')
        //     this.login()
        //     return 0
        // }
        try {
            const result = await wx.scanCode()
            console.log(result, 'fsdugyfusyuy')
            result.path = result.result || result.path
            if (!result.path || result.path.split('scene=').length === 0) {
                app.alert('请使用正确的二维码')
                return
            }
            if (result.path.includes('qrcodeType=fast-insurance') || result.path.includes('pages/fastAddInsuranceStatus/fastAddInsuranceStatus')) {
                console.log(result, '123')
                let scene = result.path.split('scene')[1]
                wx.navigateTo({
                    url: '/pages/fastAddInsuranceStatus/fastAddInsuranceStatus?scene' + scene
                })
                // }
                return
            }

            let path = result.path.split('scene=')[1]
            let cachePath = path
            if (wx.getSystemInfoSync().platform !== 'ios') {
                path = encodeURIComponent(path)
            }
            if (result.path.split('scene=')[1]) {
                wx.reportEvent('scan_click', {
                    'scan_click_num': 1
                })
                // 来自岗位的带 tJ 字段
                if (result.path.split('scene=')[1].includes('tJ')) {
                    wx.navigateTo({
                        url: '/pages/job-detail/job-detail?scene=' + cachePath,
                    })
                } else {
                    wx.navigateTo({
                        url: '/pages/join/join?scene=' + path,
                    })
                }
            } else {
                app.alert('请使用正确的小程序码')
            }

        } catch (err) {
            console.log(err)
            if (err?.errMsg !== 'scanCode:fail cancel') {
                app.alert('调用扫一扫失败')
            }
            return
        }
    },
    // 显示项目创建者信息
    async showSupplier(event) {
        const project = this.data.projectList[event.currentTarget.dataset.index]
        const text = '项目负责人：' + project.creator + '\r\n' + '联系电话：' + project.creatorPhone
        try {
            await app.confirm(text, '关闭', '呼叫')
        } catch (e) {
            wx.makePhoneCall({
                phoneNumber: project.creatorPhone
            })
        }
    },
    // 跳转到登录
    login() {
        user.goRegister()
    },
    onShareAppMessage() {
        app.toast('分享成功，感谢您的支持！')
        return {
            title: user.userName + '邀请您一起使用子弹云发工资！',
            imageUrl: '/assets/img/home/share.png'
        }
    },
    goTo(event) {
        let id = event.currentTarget.dataset.projectid
        let type = event.currentTarget.dataset.type
        // 跳转到打卡页面
        wx.navigateTo({
            url: '../../pages/detail/detail?id=' + id + '&type=' + type
        })
    },
    // 触摸
    touchMoveStartHandle(event) {
        // console.log(event.currentTarget.dataset.projectid)
        this.data.projectList.map(item => {
            if (item.projectId !== event.currentTarget.dataset.projectid) {
                item.x = 0
            }
        })
        this.setData({
            startX: event.touches[0].clientX,
            startY: event.touches[0].clientY,
            projectList: this.data.projectList
        })
    },
    touchMoveEndHandle(event) {
        // console.log(event.changedTouches[0].clientY,"touchMoveEndHandle")
        let startX = this.data.startX, // 开始X坐标
            startY = this.data.startY, // 开始Y坐标
            touchMoveEndX = event.changedTouches[0].clientX, // 滑动变化X坐标
            touchMoveEndY = event.changedTouches[0].clientY // 滑动变化Y坐标
        let angle = this.angle({
            X: startX,
            Y: startY
        }, {
            X: touchMoveEndX,
            Y: touchMoveEndY
        })
        // 防止上下滑动触发
        if (Math.abs(angle) > 50) return
        let distance = this.data.startX - event.changedTouches[0].clientX
        if (distance < 30) {
            this.setData({
                ['projectList[' + event.currentTarget.dataset.index + '].x']: 0
            })
        } else {
            this.setData({
                ['projectList[' + event.currentTarget.dataset.index + '].x']: -100
            })
        }
    },
    // 删除项目
    async leftDelete(event) {
        // console.log(event.currentTarget.dataset)
        await app.confirm('确认在列表中移除该工作吗。')
        await putLeftDelete({
            id: event.currentTarget.dataset.recordid,
            isShow: 0
        })
        app.alert('如需查看或复原，请在“我的” -- “工作记录”中操作')
        this.data.projectList = []
        this.static.hasNextPage = true
        this.static.pageNum = 1
        this.getProjectList()
    },
    // 计算滑动角度 
    angle: function (start, end) {
        var _X = end.X - start.X,
            _Y = end.Y - start.Y
        return 360 * Math.atan(_Y / _X) / (2 * Math.PI)
    },
    // 去消喜页面
    tomessage() {
        console.log('去消息页面')
        wx.navigateTo({
            url: '/pages/message/message',
        })
    },
    attention() {
        goAppList([{
            url: 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa68344cdd579b406&redirect_uri=https://front.51zidan.com/mini-auth/bullet.html?' + encodeURIComponent('openid=' + user.openid) + '&response_type=code&scope=snsapi_base#wechat_redirect',
            time: 3000
        }, {
            url: 'https://mp.weixin.qq.com/s/9SgP2C0QTwOu2AVZoJMp1Q',
            type: 'redirectTo' // 重定向跳转到关注页面，用户少返回一个界面
        }])
        this.setData({
            isAttention: true,
        })
    },
})